package com.basic.modules.nykf.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.common.exception.RRException;
import com.basic.common.utils.DateUtils;
import com.basic.common.utils.R;
import com.basic.modules.nykf.dao.CustomerShopBusinessDao;
import com.basic.modules.nykf.entity.*;
import com.basic.modules.nykf.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service("customerShopBusinessService")
public class CustomerShopBusinessServiceImpl extends ServiceImpl<CustomerShopBusinessDao, CustomerShopBusinessEntity> implements CustomerShopBusinessService {

    @Lazy
    @Autowired
    RenewManageService renewManageService;

    @Autowired
    RenewManageTwoService renewManageTwoService;

    @Autowired
    CustomerShopService customerShopService;

    @Autowired
    private CustomerShopBusinessDao customerShopBusinessDao;

    @Lazy
    @Autowired
    CustomerService customerService;

    @Autowired
    CustomerShopBusinessGroupService customerShopBusinessGroupService;

    @Override
    @Transactional
    public R addCustomerShopBusiness(CustomerShopBusinessEntity customerShopBusinessEntity) {
        // 校验店铺名重复及主业务校验
        R inspect = inspectAddOrEdit(customerShopBusinessEntity);
        if (inspect.get("code").equals(500)) {
            return inspect;
        }

        long customerId = customerShopBusinessEntity.getCustomerId();
        String sfmsVal = customerShopBusinessEntity.getSfmsVal();

        customerShopBusinessEntity.setZxl(customerShopBusinessEntity.getYwZxl());

        // 校验合并业务的结束日期是否一样
        if ("正在合作".equals(customerShopBusinessEntity.getYwhzztVal())) {

            if ("无需收费".equals(customerShopBusinessEntity.getSfmsVal())) {
                throw new RRException("正在合作状态的业务,收费模式不能为无需收费");
            }

            // 校验这个这个公司的收费模式的业务结束日期是否相同
            R r = inspectYwjssj(customerId, sfmsVal, customerShopBusinessEntity.getYwjssj(), customerShopBusinessEntity.getYwhzztVal());
            if (Integer.parseInt(r.get("code").toString()) == 500) {
                throw new RRException(r.get("msg").toString());
            }
        }

        // 修改的业务开始时间
        Date ywkssj = customerShopBusinessEntity.getYwkssj();
        Date ywjssj = customerShopBusinessEntity.getYwjssj();

        if (ywjssj.compareTo(ywkssj) < 0) {
            throw new RRException("业务结束时间不能小于业务开始时间!");
        }

        // 工作标签
        customerShopBusinessEntity.setGzbqInfo(JSONUtil.toJsonStr(customerShopBusinessEntity.getGzbqList()));
        // 如果ID存在就是update,如果不存在就是save
        if (customerShopBusinessEntity.getCustomerShopBusinessId() == null) {
            boolean save = this.save(customerShopBusinessEntity);
            if (save) {
                // 咨询量统计
                if (sfmsVal.indexOf("合并") != -1) {
                    setZxlByCustomerIdAndSfms_set(customerId, sfmsVal);
                }
            }
        } else {
            CustomerShopBusinessEntity oldYwInfo = this.getById(customerShopBusinessEntity.getCustomerShopBusinessId());

            // 业务底薪不能在业务里直接修改
            customerShopBusinessEntity.setYwdx(null);

            // 检测是不是从正在合作修改成了结束合作,或者结束合作修改成了正在合作

            // 先取当前的业务数据
            CustomerShopBusinessEntity businessInfo = this.getById(customerShopBusinessEntity.getCustomerShopBusinessId());
            String ywhzztOld = businessInfo.getYwhzztVal();
            Date ywjssjOld = businessInfo.getYwjssj();
            Date ywkssjOld = businessInfo.getYwkssj();

            String ywhzztNew = customerShopBusinessEntity.getYwhzztVal();

            if ("正在合作".equals(ywhzztOld)) {
                // 意味着业务从正在合作变为了停止合作
                if ("停止合作".equals(ywhzztNew)) {

                    // 校验 提前停止的开始日期必须等于当前的开始时间,结束日期必须小于当前的业务结束时间
                    if (ywkssj.compareTo(ywkssjOld) != 0) {
                        throw new RRException("停止合作无法修改业务开始时间!");
                    }

                    if (ywjssj.compareTo(ywjssjOld) > 0) {
                        throw new RRException("业务结束时间大于当前结束时间!");
                    }

                    // 将这个业务的收费模式改为无需收费
                    customerShopBusinessEntity.setSfmsVal("无需收费");
                    customerShopBusinessEntity.setSfmsName("无需收费");
                    customerShopBusinessEntity.setYwdx(new BigDecimal(0));
                }
            } else if ("停止合作".equals(ywhzztOld)) {
                // 意味着业务从停止合作变为了正在合作
                if ("正在合作".equals(ywhzztNew)) {
                    // 校验：恢复合作后,收费模式就不能是无需收费了
                    if ("无需收费".equals(sfmsVal)) {
                        throw new RRException("恢复合作后,收费模式不能为无需收费!");
                    }

                    // 校验,恢复的开始日期必须大于当前业务结束的结束日期
                    if (ywkssj.compareTo(ywjssjOld) <= 0) {
                        throw new RRException("业务恢复的开始日期必须大于业务结束合作时的结束日期!");
                    }

                    // 校验：把收费模式修改到某一个分组中去(如果是合并收费的话),要校验结束日期等于这个分组统一的结束日期
                    if (sfmsVal.indexOf("合并") != -1) {
                        Map map = new HashMap();
                        map.put("customerId", customerId);
                        map.put("sfmsVal", sfmsVal);
                        List<CustomerShopBusinessEntity> ywList = customerShopBusinessDao.getXfywListBySfmsValAndCustomerId(map);
                        if (ywList.size() > 0) {
                            // 校验
                            // 收费模式统一的业务结束时间
                            Date sfmstyywjssj = ywList.get(0).getYwjssj();
                            if (sfmstyywjssj.compareTo(ywjssj) != 0) {
                                throw new RRException("结束时间必须与该收费模式统一的结束时间相同!");
                            }
                        }
                    }
                }
            }
            this.updateById(customerShopBusinessEntity);

            // 计算修改之前的合并
            if (oldYwInfo.getSfmsVal().indexOf("合并") != -1) {
                setZxlByCustomerIdAndSfms_set(oldYwInfo.getCustomerId(), oldYwInfo.getSfmsVal());
            }
            // 计算修改之后的合并
            if (customerShopBusinessEntity.getSfmsVal().indexOf("合并") != -1) {
                setZxlByCustomerIdAndSfms_set(customerShopBusinessEntity.getCustomerId(), customerShopBusinessEntity.getSfmsVal());
            }
        }

        Map map = new HashMap();
        map.put("customerShopBusinessId", customerShopBusinessEntity.getCustomerShopBusinessId());
        return R.ok(map);
    }

    public static void main(String[] args) {
        JSONArray jsonArray = new JSONArray();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("customerId", 1);
        jsonObject.put("sfmsVal", "单独收费-甲");
        jsonObject.put("ywdx", "1000");

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("customerId", 1);
        jsonObject1.put("sfmsVal", "单独收费-甲");
        jsonObject1.put("ywdx", "1000");

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("customerId", 1);
        jsonObject2.put("sfmsVal", "单独收费-乙");
        jsonObject2.put("ywdx", "2000");

        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("customerId", 1);
        jsonObject3.put("sfmsVal", "单独收费-乙");
        jsonObject3.put("ywdx", "2000");

        JSONObject jsonObject4 = new JSONObject();
        jsonObject4.put("customerId", 1);
        jsonObject4.put("sfmsVal", "单独收费-丙");

        jsonArray.add(jsonObject);
        jsonArray.add(jsonObject1);
        jsonArray.add(jsonObject2);
        jsonArray.add(jsonObject3);
        jsonArray.add(jsonObject4);

        System.out.println(jsonArray.toJSONString());
    }

    // 格式：平台-店铺名-业务01
    @Override
    public R getYwmcByCustomerIdAndCustomerShopId(Map map) {
        System.out.println(map);
        String xh;
        Long customerShopId = Long.parseLong(map.get("customerShopId").toString());
        Long customerId = Long.parseLong(map.get("customerId").toString());
        List<CustomerShopBusinessEntity> ywmcList = customerShopBusinessDao.getYwmcXh(customerShopId);
        if (ywmcList.size() == 0) {
            xh = "01";
        } else {
            xh = ywmcList.get(ywmcList.size() - 1).getXh();
            int xh1 = Integer.parseInt(xh) + 1;
            if (xh1 < 10) {
                xh = "0" + xh1;
            }
        }
        return R.ok("业务" + xh);
    }

    @Override
    public void setYwdxByCustomerIdAndSfms_set(Map map) {
        long customerId = Long.parseLong(map.get("customerId").toString());
        BigDecimal ywdx = new BigDecimal(map.get("ywdx").toString());
        BigDecimal shYwdx = new BigDecimal(map.get("shYwdx").toString());
        String sfmsVal = map.get("sfmsVal").toString();

        // 先判断该客户的这个收费模式有没有数据
        QueryWrapper<CustomerShopBusinessGroupEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customerId);
        queryWrapper.eq("sfms_val", sfmsVal);
        int count = customerShopBusinessGroupService.count(queryWrapper);

        if (count == 0) {
            CustomerShopBusinessGroupEntity customerShopBusinessGroupEntity = new CustomerShopBusinessGroupEntity();
            customerShopBusinessGroupEntity.setCustomerId(customerId);
            customerShopBusinessGroupEntity.setSfmsVal(sfmsVal);
            customerShopBusinessGroupEntity.setYwdx(ywdx);
            customerShopBusinessGroupEntity.setShYwdx(shYwdx);
            customerShopBusinessGroupService.save(customerShopBusinessGroupEntity);
        } else {
            CustomerShopBusinessGroupEntity one = customerShopBusinessGroupService.getOne(queryWrapper);
            one.setYwdx(ywdx);
            one.setShYwdx(shYwdx);
            customerShopBusinessGroupService.updateById(one);
        }
    }

    @Override
    public void setZxlByCustomerIdAndSfms_set(long customerId, String sfmsVal) {
        // 先判断该客户的这个收费模式有没有数据
        QueryWrapper<CustomerShopBusinessGroupEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customerId);
        queryWrapper.eq("sfms_val", sfmsVal);
        int count = customerShopBusinessGroupService.count(queryWrapper);

        // 获取这个分组的咨询量总和
        int zxlSum = customerShopBusinessDao.getSumZxlBySfmsValAndCustomerId(customerId, sfmsVal);

        if (count == 0) {
            CustomerShopBusinessGroupEntity customerShopBusinessGroupEntity = new CustomerShopBusinessGroupEntity();
            customerShopBusinessGroupEntity.setCustomerId(customerId);
            customerShopBusinessGroupEntity.setSfmsVal(sfmsVal);
            customerShopBusinessGroupEntity.setZxl(zxlSum);
            customerShopBusinessGroupService.save(customerShopBusinessGroupEntity);
        } else {
            CustomerShopBusinessGroupEntity one = customerShopBusinessGroupService.getOne(queryWrapper);
            one.setZxl(zxlSum);
            customerShopBusinessGroupService.updateById(one);
        }
    }

    @Override
    public void setYwdxByCustomerIdAndSfms_order(List<Map> list) {
        // 先找出来这个这个客户、这个收费模式的业务集合、根据业务id排序
        for (Map map : list) {
            List<CustomerShopBusinessEntity> xfywList = customerShopBusinessDao.getXfywListBySfmsValAndCustomerId(map);
            BigDecimal ywdx = new BigDecimal(0);
            for (int i = 0; i < xfywList.size(); i++) {
                CustomerShopBusinessEntity ywInfo = xfywList.get(i);
                if (ywInfo.getYwdx() != null && ywInfo.getYwdx().compareTo(BigDecimal.ZERO) > 0) {
                    ywdx = ywInfo.getYwdx();
                }
            }
            map.put("ywdx", ywdx);
            List<Map> list1 = new ArrayList<>();
            list1.add(map);
            // setYwdxByCustomerIdAndSfms_set(list1);
        }
    }

    @Override
    public List<CustomerShopBusinessEntity> getSfmsYwListByCustomerShopBusinessId(Map map) {
        Long customerShopBusinessId = Long.parseLong(map.get("customerShopBusinessId").toString());
        // 主业务对象
        CustomerShopBusinessEntity zywObj = this.getById(customerShopBusinessId);

        Long customerId = zywObj.getCustomerId();
        String sfmsVal = zywObj.getSfmsVal();

        QueryWrapper<CustomerShopBusinessEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customerId);
        queryWrapper.eq("sfms_val", sfmsVal);
        queryWrapper.ne("is_master_val","是");
        List<CustomerShopBusinessEntity> list = this.list(queryWrapper);
        return list;
    }

    /**
     * 计算续费日期
     *
     * @param customerId 客户ID
     * @param ywjsrq     业务结束日期
     * @return
     */
    public Date calcXfrq(long customerId, Date ywjsrq) {
        CustomerEntity customer = customerService.getById(customerId);
        int xfjdVal = Integer.parseInt(customer.getXfjdVal());
        Date xfrq = DateUtils.addDateDays(ywjsrq, 0 - xfjdVal);
        return xfrq;
    }

    public R inspectAddOrEdit(CustomerShopEntity customerShopEntity) {
        // 校验是否添加了店铺业务数据
        List<CustomerShopBusinessEntity> customerShopBusinessList = customerShopEntity.getCustomerShopBusinessList();
        if (customerShopBusinessList == null || customerShopBusinessList.size() == 0) {
            return R.error("请添加店铺所属业务！");
        }

        // 校验页面层面是否重复
        boolean hasDuplicates = hasDuplicateShops(customerShopBusinessList);
        if (hasDuplicates) {
            return R.error("店铺业务名称重复,请核实！");
        }

        // 相同店铺禁止业务名称重复
        for (CustomerShopBusinessEntity customerShopBusiness : customerShopBusinessList) {

            long shopId = customerShopBusiness.getCustomerShopId();
            String ywmc = customerShopBusiness.getYwmc();
            QueryWrapper<CustomerShopBusinessEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("customer_shop_id", shopId);
            queryWrapper.eq("ywmc", ywmc);
            if (customerShopBusiness.getCustomerShopBusinessId() != null) {
                queryWrapper.ne("customer_shop_business_id", customerShopBusiness.getCustomerShopBusinessId());
            }
            int count1 = this.count(queryWrapper);
            if (count1 > 0) {
                return R.error("已存在同店铺相同的业务名称！");
            }
        }
        return R.ok();
    }

    public R inspectAddOrEdit(CustomerShopBusinessEntity customerShopBusinessEntity) {
        // 相同店铺禁止业务名称重复
        long shopId = customerShopBusinessEntity.getCustomerShopId();
        String ywmc = customerShopBusinessEntity.getYwmc();
        QueryWrapper<CustomerShopBusinessEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_shop_id", shopId);
        queryWrapper.eq("ywmc", ywmc);
        if (customerShopBusinessEntity.getCustomerShopBusinessId() != null) {
            queryWrapper.ne("customer_shop_business_id", customerShopBusinessEntity.getCustomerShopBusinessId());
        }
        int count1 = this.count(queryWrapper);
        if (count1 > 0) {
            return R.error("已存在同店铺相同的业务名称！");
        }

        String sfmsVal = customerShopBusinessEntity.getSfmsVal();
        String isMasterVal = customerShopBusinessEntity.getIsMasterVal();
        if (!sfmsVal.equals("单独收费") && !sfmsVal.equals("无需收费")) {
            QueryWrapper<CustomerShopBusinessEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("customer_shop_id", shopId);
            queryWrapper1.eq("is_master_val", "是");
            int count = this.count(queryWrapper1);
            if (count > 0 && "是".equals(isMasterVal)) {
                return R.error("该收费模式已存在主业务！");
            } else if (count == 0 && "否".equals(isMasterVal)) {
                return R.error("合并收费至少有一个主业务！");
            }
        }
        return R.ok();
    }

    public R inspectYwjssj(Long customerId, String sfmsVal, Date ywjssj, String ywhzzt) {
        // 单独的不管
        if (sfmsVal.indexOf("单独") != -1) {
            return R.ok();
        }

        Map map = new HashMap();
        map.put("customerId", customerId);
        map.put("sfmsVal", sfmsVal);
        List<CustomerShopBusinessEntity> ywList = customerShopBusinessDao.getXfywListBySfmsValAndCustomerId(map);
        if (ywList.size() > 0) {
            Date ywjssj1 = ywList.get(0).getYwjssj();
            if (ywjssj.compareTo(ywjssj1) != 0) {
                return R.error("与该收费模式的业务结束时间不统一");
            }
        }
        return R.ok();
    }

    public boolean hasDuplicateShops(List<CustomerShopBusinessEntity> customerShopBusinessList) {
        Set<String> seen = new HashSet<>();
        for (CustomerShopBusinessEntity customerShopBusiness : customerShopBusinessList) {
            String key = customerShopBusiness.getYwmc(); // 创建唯一键
            if (!seen.add(key)) { // 如果add返回false，说明已存在
                return true;
            }
        }
        return false;
    }

    /**
     * 清除空格
     *
     * @param customerShopEntity
     * @return
     */
    public CustomerShopEntity clearSpaces(CustomerShopEntity customerShopEntity) {
        // 添加店铺业务
        for (CustomerShopBusinessEntity customerShopBusinessEntity : customerShopEntity.getCustomerShopBusinessList()) {
            String ywmc = customerShopBusinessEntity.getYwmc();
            ywmc = ywmc.replace(" ", "");
            customerShopBusinessEntity.setYwmc(ywmc);
        }
        return customerShopEntity;
    }
}